﻿#region --- License & Copyright Notice
/*
CRUD Services Library

Copyright 2012 Jeevan James

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#endregion

using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;

namespace CrudServices
{
    public sealed class SearchCriteriaBuilder<TEntity> : SearchCriteriaBuilder
    {
        internal SearchCriteriaBuilder()
            : base(typeof(TEntity).Name)
        {
        }

        public SearchCriteriaBuilder<TEntity> OrderBy(params Expression<Func<TEntity, object>>[] properties)
        {
            OrderBy(GetPropertyNames(properties));
            return this;
        }

        public SearchCriteriaBuilder<TEntity> OrderByDescending(params Expression<Func<TEntity, object>>[] properties)
        {
            OrderByDescending(GetPropertyNames(properties));
            return this;
        }

        public new SearchCriteriaBuilder<TEntity> Skip(int skip)
        {
            base.Skip(skip);
            return this;
        }

        public new SearchCriteriaBuilder<TEntity> Limit(int limit)
        {
            base.Limit(limit);
            return this;
        }

        public SearchCriteriaBuilder<TEntity> Where(Expression<Func<TEntity, bool>> predicate)
        {
            var lambda = (LambdaExpression)predicate;
            var binary = (BinaryExpression)lambda.Body;

            var property = (MemberExpression)binary.Left;
            WhereOperand operand = _whereOperandMappings[binary.NodeType];
            object value = GetExpression(binary);

            Where(property.Member.Name, operand, value);
            return this;
        }

        private static object GetExpression(Expression expression)
        {
            var ce = expression as ConstantExpression;
            if (ce != null)
                return ce.Value;

            var me = expression as MemberExpression;
            if (me != null)
            {
                var constantExpression = me.Expression as ConstantExpression;
                object fieldInstance = null;
                FieldInfo fieldInfo;
                const BindingFlags FieldBindings = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance;
                if (constantExpression != null)
                {
                    fieldInfo = constantExpression.Value.GetType().GetField(me.Member.Name, FieldBindings);
                    fieldInstance = constantExpression.Value;
                } else
                    fieldInfo = me.Member.DeclaringType.GetField(me.Member.Name, FieldBindings);
                return fieldInfo.GetValue(fieldInstance);
            }

            return null;
        }

        private static string[] GetPropertyNames(IList<Expression<Func<TEntity, object>>> properties)
        {
            var result = new string[properties.Count];
            for (int i = 0; i < properties.Count; i++)
                result[i] = GetPropertyName(properties[i]);
            return result;
        }

        private static string GetPropertyName(Expression<Func<TEntity, object>> property)
        {
            var lambda = (LambdaExpression)property;
            var memberExpression = (MemberExpression)lambda.Body;
            return memberExpression.Member.Name;
        }

        private static readonly Dictionary<ExpressionType, WhereOperand> _whereOperandMappings = new Dictionary<ExpressionType, WhereOperand> {
            { ExpressionType.Equal, WhereOperand.Equals },
            { ExpressionType.NotEqual, WhereOperand.DoesNotEqual },
            { ExpressionType.GreaterThan, WhereOperand.GreaterThan },
            { ExpressionType.GreaterThanOrEqual, WhereOperand.GreaterThanOrEquals },
            { ExpressionType.LessThan, WhereOperand.LessThan },
            { ExpressionType.LessThanOrEqual, WhereOperand.LessThanOrEquals },
        };
    }
}